#pragma once
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

class DataWriter
{
private:
	int width, height, channel, frameIdx;

protected:
	FILE *mDataFile, *mMetaFile;

public:
	DataWriter(char datafilename[], char metafilename[], char metaDesc[]) {
		mDataFile = fopen(datafilename, "wb");
		if (mDataFile == NULL) {
			cout << "data file open failed." << endl;
		}

		mMetaFile = fopen(metafilename, "w");
		if (mMetaFile == NULL) {
			cout << "meta file open failed." << endl;
		}
		fprintf(mMetaFile, "#%s\n", metaDesc);

		width = 0;
		height = 0;
		frameIdx = 0;
	}

	~DataWriter(void) {
		if (mMetaFile != NULL || mDataFile != NULL)
			Release();
	}

	void Release(void) {
		fprintf(mMetaFile, "#total frames = %d.", frameIdx);

		if (mMetaFile != NULL)
			fclose(mMetaFile);
		if (mDataFile != NULL)
			fclose(mDataFile);

		mMetaFile = NULL;
		mDataFile = NULL;
	}


	void Init(int w, int h, int c)
	{
		width = w;
		height = h;
		channel = c;
		fprintf(mMetaFile, "%d %d %d\n", w, h, c);
	}

	template<typename T>
	int Write(T *ptr, long long deviceRecTime = -1)
	{
		if (width == 0 || height == 0)
			return 1;
		
		SYSTEMTIME st;
		GetSystemTime(&st);

		fwrite(ptr, sizeof(T), channel * width * height, mDataFile);
		fprintf(mMetaFile, "%5d %9d  %lld  %02d/%02d %02d:%02d:%02d.%03d\n",
				frameIdx++, clock(), deviceRecTime, st.wMonth, st.wDay,
				st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

		return 0;
	}
};

